<template>
  <div class="search-container">
    <form action="/">
        <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296FA"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow=false"
        >
            <template #action>
                <div  @click="onCancel">取消</div>
            </template>
        </van-search>
    </form>
    <!-- 搜索结果 -->
    <SearchResult  v-if="isResultShow" :searchText="searchText"/>
    <!-- 搜索结果 -->
    <!-- 联想建议 -->
    <SearchSuggestion v-else-if="searchText" :searchText="searchText" @search="onSearch"/>
    <!-- 联想建议 -->
    <!-- 搜索历史 -->
    <searchHistory v-else :deleteAll.sync="searchHistories" @showRes="onSearch" :searchHistories="searchHistories" @clear="(index)=>{searchHistories.splice(index,1)}"/>
    <!-- 搜索历史 -->
  </div>
</template>

<script>
import searchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/util/storage.js'
export default {
  name: 'SearchPage',
  components: {
    searchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data () {
    return {
      // 头部搜索框的绑定值
      searchText: '',
      // 控制搜索结果的显示状态
      isResultShow: false,
      // 存储历史记录
      searchHistories: getItem('serach-histories') || []
    }
  },
  computed: {},
  watch: {
    searchHistories (val) {
      setItem('serach-histories', val)
    }
  },
  created () {},
  methods: {
    onSearch (val) {
      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      this.searchHistories.unshift(val)
      this.searchHistories = Array.from(new Set(this.searchHistories))
      //   const { searchHistories } = this
      //   const index = searchHistories.indexOf(val)
      //   if (index !== -1) {
      //     searchHistories.splice(index, 1)
      //   } else {
      //     searchHistories.unshift(val)
      //   }
      this.searchText = val
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
    .search-container {
    .van-search__action {
        color: #fff;
    }
    }
</style>
